package main

import (
	"bytes"
	"encoding/json"
	"flag"
	"fmt"
	"io/ioutil"
	"net/http"
	"peilian-api/app/global/databases/tables"
	"peilian-api/app/global/variable"
	"peilian-api/app/model"
	_ "peilian-api/bootstrap"
)

type StuInfo struct {
	School         string `json:"school"`
	College        string `json:"college"`
	Specialty      string `json:"specialty"`
	DateOfenTrance string `json:"dateofentrance"`
	Level          string `json:"level"`
	Name           string `json:"name"`
	Studentpin     string `json:"studentpin"`
}

func parseResponse(response *http.Response) (map[string]interface{}, error) {
	var result map[string]interface{}
	body, err := ioutil.ReadAll(response.Body)
	if err == nil {
		err = json.Unmarshal(body, &result)
	}

	return result, err
}
func httpRequest(method string, url string, jsonStr string) map[string]interface{} {
	req, _ := http.NewRequest(method, url, bytes.NewBuffer([]byte(jsonStr)))
	req.Header.Set("Content-type", "application/json")
	req.Header.Set("token", "WA78ILMTQHvrVfGv3XFQRg==")
	client := &http.Client{}
	response, err := client.Do(req)

	if err == nil {
		// 解析Response
		m, _ := parseResponse(response)
		return m
	}
	return map[string]interface{}{}
}

func GetConstituteIdByName(name string) uint {
	var cons tables.Constitute
	variable.DB.MySQL.Model(&cons).Where("name = ?", name).Find(&cons)
	return cons.ID
}

func assembleGivenData(cons []model.CfgInfos) map[string]map[string]map[string]uint {
	mp := map[string]map[string]map[string]uint{}
	for _, school := range cons {
		a := map[string]map[string]uint{}
		for _, academy := range school.Value {
			p := map[string]uint{}
			for _, profession := range academy.Value {
				p[profession.Name] = profession.Id
			}
			a[academy.Name] = p
		}
		mp[school.Name] = a
	}
	// b, _ := json.Marshal(mp)
	return mp
}

// 操作方法  go run scripts/beida/curl_student.go -grade 2018
// 北京大学 agent_id 25
// 北京大学 consititute_id  582
func main() {
	var grade string
	var schoolName string
	flag.StringVar(&grade, "grade", "2022", "年级，默认是2022")
	flag.StringVar(&schoolName, "school", "北京大学", "学校，默认是北京大学")
	flag.Parse()

	fmt.Println(grade)
	fmt.Println(schoolName)

	// 获取北京大学的id
	schoolId := GetConstituteIdByName(schoolName)

	// 查询数据
	ci, _ := new(tables.Constitute).GetAllInfoBySchoolId(int(schoolId))
	consMap := assembleGivenData(ci)

	// b, _ := json.Marshal(consMap)
	// fmt.Println(string(b))

	// 先查询数据
	var stMap map[string]map[string]map[string]int = make(map[string]map[string]map[string]int, 0)
	var sios []StuInfo
	m := httpRequest("GET", fmt.Sprintf("https://scc.pku.edu.cn/api-data!studentList.action?year=%s", grade), "")
	b, _ := json.Marshal(m["data"])
	json.Unmarshal(b, &sios)
	for i := 0; i < len(sios); i++ {
		var stu = sios[i]
		_, ok := stMap[stu.School]
		if !ok {
			var collegeMap map[string]map[string]int = make(map[string]map[string]int, 0)
			stMap[stu.School] = collegeMap
		}
		if len(stu.College) == 0 {
			continue
		}
		_, ok = stMap[stu.School][stu.College]
		if !ok {
			var specialtyMap map[string]int = make(map[string]int, 0)
			stMap[stu.School][stu.College] = specialtyMap
		}
		if len(stu.Specialty) == 0 {
			continue
		}
		_, ok = stMap[stu.School][stu.College][stu.Specialty]
		if !ok {
			stMap[stu.School][stu.College][stu.Specialty] = 0
		}
	}

	// b, _ = json.Marshal(stMap)
	// fmt.Println(string(b))

	for college, vs := range stMap[schoolName] {
		var consCollege = tables.Constitute{
			BelongToID: &schoolId,
			Type:       "academy",
			Name:       college,
		}
		_, ok := consMap[schoolName][college]
		if ok { // 不用插入，只需要查询id
			variable.DB.MySQL.Where("name = ? and belong_to_id = ?", college, schoolId).Find(&consCollege)
		} else {
			variable.DB.MySQL.Model(&tables.Constitute{}).Create(&consCollege)
		}
		for profession, _ := range vs {
			if _, ok := consMap[schoolName][college][profession]; ok {
				continue
			}
			var consCollege = tables.Constitute{
				BelongToID: &consCollege.ID,
				Type:       "profession",
				Name:       profession,
			}
			variable.DB.MySQL.Model(&consCollege).Create(&consCollege)
		}
	}
}
